//
//  ViewController.m
//  WaterFlowStyle
//
//  Created by  on 12-5-16.
//  Copyright (c) 2012年 Taobao. All rights reserved.
//




#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>

#import "UICustomImageView.h"
#import "CouponManager.h"
#import "Coupon.h"
#import "CouponCon.h"
#import "Constants.h"
@implementation ViewController

@synthesize waterFlowView = _waterFlowView;
@synthesize dataArray = _dataArray;
@synthesize imageArray = _imageArray;
@synthesize imageArray2=_imageArray2;



//- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
//{
//    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
//    if (self) {
//        UITabBarItem *item = [[UITabBarItem alloc]initWithTabBarSystemItem:UITabBarSystemItemMostRecent tag:1];
//        self.tabBarItem = item;
//
//    }
//    return self;
//}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title=@"活动";
    [self.view setBackgroundColor:[UIColor whiteColor]];
    CGRect rect = self.view.frame;
    rect.size.height -= 150;


    
    self.waterFlowView=[[WaterFlowView alloc]initWithFrame:CGRectMake(0, 0, 320, SScouponConImg)];
    [self.view addSubview:self.waterFlowView];
    self.waterFlowView.waterFlowDataSource = self;
    self.waterFlowView.waterFlowDelegate = self;
    self.waterFlowView.decelerationRate=0.1f;
    
    
    
    
//    UIButton *button=[[UIButton alloc]initWithFrame:CGRectMake(x,y, 162, 40)];
//    
//    //不高亮显示
//    button.adjustsImageWhenHighlighted=NO;
//    //设置按钮内容
//    [button setTitle:supplierCategory.supplierCategoryName forState:UIControlStateNormal];
//    //商铺类型字体：18  标题1
//    //        button.titleLabel.font=[UIFont fontWithName:@"Helvetica" size:18];
//    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    //设置按钮tag
//    [button setTag:supplierCategory.supplierCategoryId];
//    NSString *filePath=[[NSBundle mainBundle] pathForResource:@"supplierCategorieBtnBg" ofType:@"png"];
//    [button setBackgroundImage:[UIImage imageWithContentsOfFile:filePath] forState:UIControlStateNormal];
//    
//    NSString *filePath2=[[NSBundle mainBundle] pathForResource:@"supplierCategorieBtnBgChange" ofType:@"png"];
//    [button setBackgroundImage:[UIImage imageWithContentsOfFile:filePath2] forState:UIControlStateHighlighted];
//    [button addTarget:self action:@selector(showShopBtnDelay:) forControlEvents:UIControlEventTouchUpInside];
//    [view addSubview:button];
    
    
    moreBtn=[[UIButton alloc]initWithFrame:CGRectMake(0, SScouponConAdd,320, 50)];
    
    moreBtn.adjustsImageWhenHighlighted=NO;
    
    [moreBtn setTitle:@"加载下10条" forState:UIControlStateNormal];
    [moreBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    
    NSString *filePath=[[NSBundle mainBundle] pathForResource:@"shopBtnBg" ofType:@"png"];
    [moreBtn setBackgroundImage:[UIImage imageWithContentsOfFile:filePath] forState:UIControlStateNormal];
    
    
    [moreBtn addTarget:self action:@selector(addDataHud) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:moreBtn];
    
//    moreBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//    moreBtn.frame =CGRectMake(0,317,320, 50);
//    
//    [moreBtn setTitle:@"加载下10条" forState:UIControlStateNormal];
//    [self.view addSubview:moreBtn];
//    [moreBtn addTarget:self action:@selector(addDataHud) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    
    //初始化hud
    HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    [self.navigationController.view addSubview:HUD];
	HUD.dimBackground = YES;
    HUD.delegate=self;
    [HUD showWhileExecuting:@selector(firstLoad)onTarget:self withObject:Nil animated:YES];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:NO];
    isTouched=YES;
    //隐藏导航栏
    self.navigationController.navigationBar.hidden=YES;
}





-(void)firstLoad{
    currentPage = 1;
    couponManager=[[CouponManager alloc]init];
    self.imageArray= [couponManager getCouponsByCondition:@"1" pageIndex:@"1" pageSize:@"5"];
    
    self.imageArray2=[couponManager getCouponsByCondition:@"2" pageIndex:@"1" pageSize:@"5"];
    
    
    self.dataArray = [NSMutableArray arrayWithCapacity:2];
    for (int i = 0; i < 2; ++i) {
        NSMutableArray *array = [NSMutableArray array];
        [self.dataArray addObject:array];
    }
    for (int i = 0; i < [self.dataArray count]; ++i) {
        NSMutableArray *array = [self.dataArray objectAtIndex:i];
        for (int j = 0; j < [self.imageArray count]; ++j) {
            if(i==0){
                Coupon *coupon=[self.imageArray objectAtIndex:j];
                NSString *imageUrl = coupon.SmallImgUrl;
                
                [array addObject:imageUrl];
            }
            if(i==1){
                Coupon *coupon=[self.imageArray2 objectAtIndex:j];
                NSString *imageUrl = coupon.SmallImgUrl;
                
                [array addObject:imageUrl];
            }
        }
    }
    //点击进入设置tabbar为nil
//    self.navigationController.tabBarItem.badgeValue=nil;
    
    [self.waterFlowView reloadData];
}

- (void)addDataHud
{
    [HUD showWhileExecuting:@selector(addData) onTarget:self withObject:nil animated:YES];
}

-(void)addData{
    
    currentPage++;
    NSString *currentPageString=[NSString stringWithFormat: @"%d", currentPage];
    
    NSArray * newCoupon = [couponManager getCouponsByCondition:@"1" pageIndex:currentPageString pageSize:@"5"];
    if([newCoupon count]==0){
        moreBtn.titleLabel.text=@"已全部加载";
    }
    
    if(newCoupon !=Nil) {
        self.imageArray = [self.imageArray arrayByAddingObjectsFromArray:newCoupon];
    }
    
    NSArray *newCoupon2=[couponManager getCouponsByCondition:@"2" pageIndex:currentPageString pageSize:@"5"];
    if(newCoupon2 !=Nil) {
        self.imageArray2 = [self.imageArray2 arrayByAddingObjectsFromArray:newCoupon2];
    }
    
    self.dataArray = [NSMutableArray arrayWithCapacity:2];
    for (int i = 0; i < 2; ++i) {
        NSMutableArray *array = [NSMutableArray array];
        [self.dataArray addObject:array];
    }
    for (int i = 0; i < [self.dataArray count]; ++i) {
        NSMutableArray *array = [self.dataArray objectAtIndex:i];
        for (int j = 0; j < [self.imageArray count]; ++j) {
            if(i==0){
                Coupon *coupon=[self.imageArray objectAtIndex:j];
                NSString *imageUrl = coupon.SmallImgUrl;
                [array addObject:imageUrl];
            }
            if(i==1){
                Coupon *coupon=[self.imageArray2 objectAtIndex:j];
                NSString *imageUrl = coupon.SmallImgUrl;
                [array addObject:imageUrl];
            }
        }
    }
    [self.waterFlowView reloadData];
}

- (NSInteger)waterFlowView:(WaterFlowView *)waterFlowView numberOfRowsInColumn:(NSInteger)column
{
    return [[self.dataArray objectAtIndex:column] count];
}

- (WaterFlowViewCell *)waterFlowView:(WaterFlowView *)waterFlowView cellForRowAtIndexPath:(WFIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"WaterFlowViewCell";
    WaterFlowViewCell *cell = [self.waterFlowView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (nil == cell) {
#ifdef DEBUG
        
#endif
        cell = [[[WaterFlowViewCell alloc] initWithIdentifier:cellIdentifier] autorelease];
        UICustomImageView *imageView = [[UICustomImageView alloc] initWithFrame:CGRectZero];
        imageView.tag = 50;
        [cell addSubview:imageView];
        [imageView release];
    } else
    {
#ifdef DEBUG
        
#endif
    }
    //高
    float tempHight=[self waterFlowView:nil heightForRowAtIndexPath:indexPath];
    NSString *imageUrl = [[self.dataArray objectAtIndex:indexPath.column] objectAtIndex:indexPath.row];
    UICustomImageView *imageView = (UICustomImageView *)[cell viewWithTag:50];
    imageView.frame = CGRectMake(2, 0, 155, tempHight);
    imageView.opaque=YES;
    [imageView setUserInteractionEnabled:NO];
    [imageView setImage:nil];
    [imageView setImageURL:imageUrl];
    UIButton *imgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    imgBtn.frame=CGRectMake(10, 0, 160, tempHight);
    [imgBtn setShowsTouchWhenHighlighted:YES];
    
    if(indexPath.column==0){
        Coupon *coupon=[self.imageArray objectAtIndex:indexPath.row];
        imgBtn.tag=coupon.Id;
    }
    if(indexPath.column==1){
        Coupon *coupon=[self.imageArray2 objectAtIndex:indexPath.row];
        imgBtn.tag=coupon.Id;
    }
    
    
    
    
    [imgBtn addTarget:self action:@selector(showCouponCon:) forControlEvents:UIControlEventTouchUpInside];
    [cell addSubview:imgBtn];
    return cell;
}

- (IBAction)showCouponCon:(id)sender {
    
    if(isTouched){
        isTouched=NO;
        //创建新的试图并将试图推入栈中
        CouponCon *couponCon = [[CouponCon alloc]init];
        //        NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity :1];
        //        [dictionary setObject:supIdToString forKey:@"supId"];
        //        [dictionary setObject:[sender titleForState:UIControlStateNormal] forKey:@"supName"];
        //        [dictionary setObject:@"mainPageHistoryBtnClickedNew" forKey:@"source"];//用户统计到友盟时的来源判断
        //        [detailShopViewController setRecieveDictionary:dictionary];
        couponCon.id=[sender tag];
        couponCon.imageArray=self.imageArray;
        couponCon.imageArray2=self.imageArray2;
        [self.navigationController pushViewController: couponCon animated:YES];
        [couponCon release];
    }
    
}

- (CGFloat)waterFlowView:(WaterFlowView *)waterFlowView heightForRowAtIndexPath:(WFIndexPath *)indexPath
{
    float height = 0;
	switch ((indexPath.row + indexPath.column )  % 5) {
		case 0:
			height = 127;
			break;
		case 1:
			height = 105;
			break;
		case 2:
			height = 100;
			break;
		case 3:
			height = 114;
			break;
		case 4:
			height = 140;
			break;
		default:
			break;
	}
	height += indexPath.row + indexPath.column;
	return height;
}

- (NSInteger)numberOfColumnsInWaterFlowView:(WaterFlowView *)waterFlowView
{
    return [self.dataArray count];
}

#pragma mark - WaterFlowViewDelegate

//- (void)waterFlowView:(WaterFlowView *)waterFlowView didSelectRowAtIndexPath:(WFIndexPath *)indexPath
//{
//    NSLog(@"select%d",[indexPath row]);
//}





- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (void)dealloc
{
    [_waterFlowView release];
    [_dataArray release];
    [_imageArray release];
    [_imageArray2 release];
    [HUD release];
    [couponManager release];
    [super dealloc];
}

- (void)viewDidUnload
{

    couponManager=nil;
    self.dataArray=nil;
    self.imageArray=nil;
    self.imageArray2=nil;
    self.waterFlowView = nil;
    [super viewDidUnload];
}

@end
